/*******************************************************************/
/* @ All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.        */
/*                                                                 */
/*  NAME      = wtc_core.c                                        */
/*  NOTE      =                                                    */
/*  DATE      = 2015/08/13 by songbb                               */
/*******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

#include "frcomm.h"
#include "frhash2.h"
#include "frmem.h"
#include "frlog.h"
#include "frsutl.h"

#include "conntrack.h"
#include "frct_comm.h"

#include "wtc_comm.h"
#include "wtc_header.h"
#include "wtc_packet.h"
#include "wtc_tfmh.h"

/*******************************************************************************
*  FUNC     :  WTC Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __wtc_private_session_init(L7_session *p_st_session)
{
    WTC_PRINT_INFO("session init\n");
    L7session_wtc_private *p_st_wtc_private = NULL;      // WTC的私有信息
    L7session_wtc *p_st_wtc_sess = NULL;                 // WTC的私有session信息
    L7_wtc_packet *p_st_wtc_packet = NULL;               // WTC格式的packet包
    L7_wtc_stmt *p_st_wtc_stmt = NULL;                   // WTC消息指令

    // 1. 初始化WTC的私有session信息
    if ((p_st_wtc_sess = (L7session_wtc *) frmalloc(sizeof(L7session_wtc))) == NULL)
    {
        WTC_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_wtc_sess, 0x00, sizeof(L7session_wtc));
    p_st_wtc_sess->p_default_encoding = frstrdup("gb18030");

#if APM_WTC_DBG
    p_st_wtc_sess->st_timestamp.tv_sec = 0L;
    p_st_wtc_sess->st_timestamp.tv_usec = 0L;
#endif

    // 2. 初始化WTC格式的packet包
    if ((p_st_wtc_packet = (L7_wtc_packet *) frmalloc(sizeof(L7_wtc_packet))) == NULL)
    {
        WTC_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_wtc_packet, 0x00, sizeof(L7_wtc_packet));
    if (wtc_init_packet(p_st_wtc_packet) != FR_SUCC)
        goto error;

    // 3. 初始化WTC消息指令
    if ((p_st_wtc_stmt = (L7_wtc_stmt *) frmalloc(sizeof(L7_wtc_stmt))) == NULL)
    {
        WTC_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_wtc_stmt, 0x00, sizeof(L7_wtc_stmt));
    p_st_wtc_stmt->p_list_mbstring = frlist_create();

    // 4. 创建和初始化WTC的私有信息
    if ((p_st_wtc_private = (L7session_wtc_private *) frmalloc(sizeof(L7session_wtc_private))) == NULL)
    {
        WTC_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_wtc_private, 0x00, sizeof(L7session_wtc_private));
    p_st_wtc_private->p_st_sess = p_st_wtc_sess;
    p_st_wtc_private->p_st_wtc_packet = p_st_wtc_packet;
    p_st_wtc_private->p_st_session = p_st_session;
    p_st_wtc_private->p_st_wtc_stmt = p_st_wtc_stmt;

    // 5. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_wtc_private);

    return FR_SUCC;
error:
    wtc_free((void **) &p_st_wtc_private);
    return FR_FAIL;
}

/*******************************************************************************
*  FUNC     :  分析数据方向
*  ARGS     :  p_payload                              (数据内容)
*  ARGS     :  ui_payload_len                         (数据长度)
*  RTN      :  0x00                                     (FR_DIRECT_UNKNOWN)
*              0x02                                     (FR_DIRECT_SRV2CLIENT)
*              0x03                                     (FR_DIRECT_CLIENT2SRV)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __wtc_analyze_direct(char *p_payload
                                    , unsigned int ui_payload_len)
{
    unsigned int *p_ui_magic;
    unsigned int ui_magic;
    unsigned int *p_ui_opcode;
    unsigned int ui_opcode = 0;
    int i_direction = FR_DIRECT_UNKNOWN;

    p_ui_magic = (unsigned int *) p_payload;
    ui_magic = (unsigned int) ntohl(*p_ui_magic);

    if (ui_magic == APM_WTC_HEADER_SMAGIC)
    {
        p_ui_opcode = (unsigned int *) (p_payload + 4);
        ui_opcode = (unsigned int) ntohl(*p_ui_opcode);
        return wtc_analyze_direction_by_opcode(ui_opcode);
    }
    else
    {
        if (ui_payload_len < 36)
            return FR_DIRECT_UNKNOWN;

        if (wtc_tfmh_fad(p_payload, ui_payload_len, &i_direction) == FR_SUCC)
            return i_direction;
    }

    return FR_DIRECT_UNKNOWN;
}

/*******************************************************************************
*  FUNC     :  判断当前数据链路是否是WTC协议的
*  ARGS     :  *p_st_conn                           (ct信息)
*           :  *p_st_packet                        (协议分析入力数据)
*  RTN      :  参照module.h中APM_L7_IS_的定义
*  NOTE     :
*******************************************************************************/
int wtc_detect(Conntrack *p_st_conn
             , Apm_packet *p_st_packet)
{
    WTC_PRINT_INFO("wtc_detect\n");
    int i_analyzed_direct = 0;
    char *p_inflated_payload = NULL;
    unsigned int ui_inflated_payload_len = 0;

    if(p_st_conn == NULL || p_st_packet==NULL)
        return APM_L7_IS_UNKNOWN;

#if APM_WTC_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));
    WTC_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    WTC_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_packet->ui_payload_len);
#endif

    int i_ret = wtc_header_detect(p_st_packet->p_payload, p_st_packet->ui_payload_len, &p_inflated_payload, &ui_inflated_payload_len);
    if (i_ret == APM_L7_IS_YES)
    {
        // 设置方向
        WTC_PRINT_WARN("p_st_packet->i_direction:[%d:%s] frct_get_direct_known(p_st_conn):[%d:%s]\n",
                       p_st_packet->i_direction,
                       WTC_DIRECT2STR(p_st_packet->i_direction),
                       frct_get_direct_known(p_st_conn),
                       WTC_DIRECT2STR(frct_get_direct_known(p_st_conn)));
        if (p_st_packet->i_direction == FR_DIRECT_UNKNOWN || frct_get_direct_known(p_st_conn) == FR_DIRECT_UNKNOWN)
        {
            if (p_inflated_payload)
                i_analyzed_direct = __wtc_analyze_direct(p_inflated_payload, ui_inflated_payload_len);
            else
                i_analyzed_direct = __wtc_analyze_direct(p_st_packet->p_payload, p_st_packet->ui_payload_len);

            if (i_analyzed_direct == FR_DIRECT_CLIENT2SRV)
            {
                WTC_PRINT_CRIT("Set Server:[%s:%d]\n", arr_ip_dst, p_st_packet->dst_port);
                if (frcap_set_cs_srv(p_st_conn, p_st_packet->dst_ip, p_st_packet->dst_port) != FR_SUCC)
                    goto unknown;
            }
            else if (i_analyzed_direct == FR_DIRECT_SRV2CLIENT)
            {
                WTC_PRINT_CRIT("Set Server:[%s:%d]\n", arr_ip_src, p_st_packet->src_port);
                if (frcap_set_cs_srv(p_st_conn, p_st_packet->src_ip, p_st_packet->src_port) != FR_SUCC)
                    goto unknown;
            }
            else
            {
                WTC_PRINT_EMERG("Can not analyze direction\n\n");
//                goto unknown;
            }
        }
    }

    if (i_ret == APM_L7_IS_UNKNOWN)
        WTC_PRINT_ERR("detect unknown\n\n");
    else
        WTC_PRINT_ERR("detect yes\n\n");

    wtc_free((void **) &p_inflated_payload);
    return i_ret;
unknown:
    wtc_free((void **) &p_inflated_payload);
    return APM_L7_IS_UNKNOWN;
}

/*******************************************************************************
*  FUNC     :  WTC协议解析
*  ARGS     :  *p_st_conn                           (ct信息)
*           :  *p_st_packet                        (协议分析入力数据)
*           :  *p_st_hash_report                    (保存Frreport_data)
*  RTN      :  参照module.h中APM_L7_ANALYZE_的定义
*  NOTE     :
*******************************************************************************/
int wtc_analyze(Conntrack *p_st_conn
              , Apm_packet *p_st_packet
              , Frhash_header *p_st_hash_report)
{
    WTC_PRINT_INFO("wtc_analyze\n");
    L7_session *p_st_session = frct_get_session(p_st_conn);
    L7session_wtc_private *p_st_session_private = NULL;
    L7session_wtc *p_st_sess = NULL;
    L7_wtc_packet *p_st_wtc_packet = NULL;
    int i_unfragmented_ret = 0;
    int i_analyze_ret = 0;                  // 本函数的返回值
    char arr_ip_src[56], arr_ip_dst[56];

    if(p_st_conn == NULL || p_st_packet == NULL || p_st_hash_report == NULL )
        return APM_L7_ANALYZE_FAIL;

    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));

    WTC_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    WTC_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_st_data_in是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_st_data_in是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_FIN || p_st_packet->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_SYN)
            WTC_PRINT_INFO("SYN PACKET\n");
        else if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_FIN)
            WTC_PRINT_INFO("FIN PACKET\n");
        if (p_st_session->p_session_private != NULL)
        {
            wtc_session_destory(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        WTC_PRINT("### i_analyze_ret:[%d]\n\n", APM_L7_ANALYZE_SUCC);
        return APM_L7_ANALYZE_SUCC;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化WTC的session数据
        if (__wtc_private_session_init(p_st_session) != FR_SUCC)
            goto wtc_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    // 打印方向
    switch (p_st_packet->i_direction)
    {
        case FR_DIRECT_CLIENT2SRV:
            WTC_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port,
                      p_st_packet->ui_payload_len);
            break;
        case FR_DIRECT_SRV2CLIENT:
            WTC_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port,
                      p_st_packet->ui_payload_len);
            break;
        default:
            WTC_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port);
            goto wtc_analyze_fail;
    }

    p_st_session_private = (L7session_wtc_private *) frct_get_session_private(p_st_session);
    p_st_sess = p_st_session_private->p_st_sess;
    p_st_wtc_packet = p_st_session_private->p_st_wtc_packet;

    i_unfragmented_ret = wtc_packet_unfragment(p_st_sess, p_st_packet, p_st_wtc_packet);
    if (i_unfragmented_ret == APM_WTC_CHECK_FRAGMENT_NEED_NEXT_PACKET)
        goto wtc_analyze_todo;
    else if (i_unfragmented_ret == APM_WTC_CHECK_FRAGMENT_ERROR)
        goto wtc_analyze_fail;

    switch (p_st_wtc_packet->em_tfmh_type)
    {
        case APM_WTC_TFMH_TYPE_DOM:
            if (wtc_tfmh_dom(p_st_conn, p_st_sess, p_st_wtc_packet, p_st_hash_report) == FR_SUCC)
            {
                i_analyze_ret = p_st_wtc_packet->i_is_req == FR_YES ? APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC) : APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
                goto wtc_analyze_success;
            }
            goto wtc_analyze_fail;
        case APM_WTC_TFMH_TYPE_ORIG:
            if (wtc_tfmh(p_st_conn, p_st_packet, p_st_sess, p_st_wtc_packet, p_st_hash_report) == FR_SUCC)
            {
                i_analyze_ret = p_st_wtc_packet->i_is_req == FR_YES ? APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC) : APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
                goto wtc_analyze_success;
            }
            goto wtc_analyze_fail;
        case APM_WTC_TFMH_TYPE_WS:
        default:
            WTC_PRINT_EMERG("invalid tfmh type\n");
            goto wtc_analyze_fail;
    }

wtc_analyze_todo:
    WTC_PRINT("### i_analyze_ret todo:[%d]\n\n", APM_L7_ANALYZE_TODO);
    return APM_L7_ANALYZE_TODO;

wtc_analyze_success:
    WTC_PRINT("### i_analyze_ret success:[%d]\n\n", i_analyze_ret);
    return i_analyze_ret;

wtc_analyze_fail:
    if (wtc_packet_is_in_fragment(p_st_wtc_packet))
    {
        if (bytebuff_setPosition(p_st_wtc_packet->p_st_packet, 0) != FR_SUCC)
        {
            p_st_wtc_packet->fragment_state = APM_WTC_FRAGMENT_INIT;
            return APM_L7_ANALYZE_FAIL;
        }
        goto wtc_analyze_todo;
    }
    else
    {
        WTC_PRINT_PACKET("error packet", p_st_wtc_packet);
        wtc_init_packet(p_st_wtc_packet);
    }

    WTC_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7session_wtc
*  ARGS     :  **pp_st_session              (L7session_wtc)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __wtc_destroy_session(L7session_wtc **pp_st_session)
{
    if (pp_st_session == NULL || *pp_st_session == NULL)
        return;

    L7session_wtc *p_st_sess = *pp_st_session;
    wtc_free((void **) &(p_st_sess->p_service_name));
    wtc_free((void **) &(p_st_sess->p_client_domainid));
    wtc_free((void **) &(p_st_sess->p_service_domainid));
    wtc_free((void **) &(p_st_sess->p_default_encoding));
    wtc_free((void **) &(p_st_sess->p_codeset_encoding));
    wtc_free((void **) pp_st_session);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_wtc_packet
*  ARGS     :  **pp_st_wtc_packet              (L7_wtc_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __wtc_destroy_packet(L7_wtc_packet **pp_st_wtc_packet)
{
    if (pp_st_wtc_packet == NULL || *pp_st_wtc_packet == NULL)
        return;

    L7_wtc_packet *p_st_wtc_packet = *pp_st_wtc_packet;
    bytebuff_free(&(p_st_wtc_packet->p_st_packet));
    wtc_free((void **) pp_st_wtc_packet);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_wtc_stmt
*  ARGS     :  **pp_st_wtc_stmt              (L7_wtc_stmt)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __wtc_destroy_stmt(L7_wtc_stmt **pp_st_wtc_stmt)
{
    return wtc_free_stmt(pp_st_wtc_stmt);
}

/*******************************************************************************
*  FUNC     :  释放WTC private数据
*  ARGS     :  *p_st_session_private_in                 (WTC的私有信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
int wtc_session_destory(void *p_st_session_private_in)
{
    WTC_PRINT(KBLUE "\nwtc_session_destory run\n" RESET);
    if (p_st_session_private_in == NULL)
        return FR_SUCC;

    L7session_wtc_private *p_st_private = (L7session_wtc_private *) p_st_session_private_in;

    __wtc_destroy_session(&(p_st_private->p_st_sess));

    __wtc_destroy_packet(&(p_st_private->p_st_wtc_packet));

    __wtc_destroy_stmt(&(p_st_private->p_st_wtc_stmt));

    frreport_body_l7list_free(&(p_st_private->p_report_comm));
    frreport_body_l7list_free(&(p_st_private->p_report_req));

    wtc_free((void **) &p_st_private);

    WTC_PRINT_INFO("leave wtc_session_destory\n");
    return FR_SUCC;
}
